// Library.java (更新版)
package Object.work.model;

import Object.work.exception.BookNotFoundException;
import Object.work.exception.DuplicateBookException;
import Object.work.exception.InvalidOperationException;
import Object.work.exception.UserNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Library {
    private List<LibraryItem> items;
    private List<User> users;

    public Library() {
        this.items = new ArrayList<>();
        this.users = new ArrayList<>();
    }

    // 添加图书项
    public void addItem(LibraryItem item) throws DuplicateBookException {
        if (items.stream().anyMatch(i -> i.getId().equals(item.getId()))) {
            throw new DuplicateBookException("Book with ID " + item.getId() + " already exists");
        }
        items.add(item);
    }

    // 添加用户
    public void addUser(User user) throws DuplicateBookException {
        if (users.stream().anyMatch(u -> u.getId().equals(user.getId()))) {
            throw new DuplicateBookException("User with ID " + user.getId() + " already exists");
        }
        users.add(user);
    }

    // 获取所有图书项
    public List<LibraryItem> getAllItems() {
        return new ArrayList<>(items);
    }

    // 获取所有用户
    public List<User> getAllUsers() {
        return new ArrayList<>(users);
    }

    // 根据ID查找图书项
    public LibraryItem findItemById(String id) throws BookNotFoundException {
        return items.stream()
                .filter(item -> item.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new BookNotFoundException("Book with ID " + id + " not found"));
    }

    // 根据ID查找用户
    public User findUserById(String id) throws UserNotFoundException {
        return users.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new UserNotFoundException("User with ID " + id + " not found"));
    }

    // 更新图书信息
    public void updateItem(String id, LibraryItem newItem)
            throws BookNotFoundException, DuplicateBookException {
        LibraryItem existingItem = findItemById(id);

        // 检查新ID是否与其他图书冲突
        if (!id.equals(newItem.getId()) &&
                items.stream().anyMatch(i -> i.getId().equals(newItem.getId()))) {
            throw new DuplicateBookException("Book with ID " + newItem.getId() + " already exists");
        }

        items.remove(existingItem);
        items.add(newItem);
    }

    // 更新用户信息
    public void updateUser(String id, User newUser)
            throws UserNotFoundException, DuplicateBookException {
        User existingUser = findUserById(id);

        // 检查新ID是否与其他用户冲突
        if (!id.equals(newUser.getId()) &&
                users.stream().anyMatch(u -> u.getId().equals(newUser.getId()))) {
            throw new DuplicateBookException("User with ID " + newUser.getId() + " already exists");
        }

        users.remove(existingUser);
        users.add(newUser);
    }

    // 删除图书
    public void deleteItem(String id) throws BookNotFoundException {
        LibraryItem item = findItemById(id);
        items.remove(item);
    }

    // 删除用户
    public void deleteUser(String id) throws UserNotFoundException {
        User user = findUserById(id);
        users.remove(user);
    }

    // 搜索图书(按标题)
    public List<LibraryItem> searchItemsByTitle(String keyword) {
        return items.stream()
                .filter(item -> item.getTitle().toLowerCase().contains(keyword.toLowerCase()))
                .collect(Collectors.toList());
    }

    // 搜索用户(按名称)
    public List<User> searchUsersByName(String keyword) {
        return users.stream()
                .filter(user -> user.getName().toLowerCase().contains(keyword.toLowerCase()))
                .collect(Collectors.toList());
    }

    // 借书
    public void borrowItem(String itemId, String userId)
            throws BookNotFoundException, UserNotFoundException, InvalidOperationException {
        LibraryItem item = findItemById(itemId);
        User user = findUserById(userId);

        if (item instanceof PhysicalBook) {
            PhysicalBook physicalBook = (PhysicalBook) item;
            if (!physicalBook.isAvailable()) {
                throw new InvalidOperationException("Book is not available for borrowing");
            }
            physicalBook.setAvailable(false);
        } else {
            throw new InvalidOperationException("Only physical books can be borrowed");
        }
    }

    // 还书
    public void returnItem(String itemId) throws BookNotFoundException, InvalidOperationException {
        LibraryItem item = findItemById(itemId);

        if (item instanceof PhysicalBook) {
            PhysicalBook physicalBook = (PhysicalBook) item;
            if (physicalBook.isAvailable()) {
                throw new InvalidOperationException("Book is already available");
            }
            physicalBook.setAvailable(true);
        } else {
            throw new InvalidOperationException("Only physical books can be returned");
        }
    }
}